﻿/*********************************************************************************
 *Author:         OnClick
 *Version:        1.0
 *UnityVersion:   2018.3.1f1
 *Date:           2019-03-26
 *Description:    IFramework
 *History:        2018.11--
*********************************************************************************/
using System;
using System.Text;

namespace IFramework
{
    public class ClientPackage : DataFrameInfo
    {
        private Encoding encoding = Encoding.UTF8;
        private readonly string[] splitChars = null;
        public ClientPackage()
        {
            splitChars = new string[] { ": " };
        }
        public string ReqAccessPackage()
        {
            return new AccessInfo().ToString();
        }
        public AcceptInfo GetAcceptPackage(string msg)
        {
            string[] msgs = msg.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var acceptInfo = new AcceptInfo();
            acceptInfo.HttpProto = msgs[0];
            foreach (var item in msgs)
            {
                string[] kv = item.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                switch (kv[0])
                {
                    case "Upgrade":
                        acceptInfo.Upgrade = kv[1];
                        break;
                    case "Connection":
                        acceptInfo.Connection = kv[1];
                        break;
                    case "Sec-WebSocket-Accept":
                        acceptInfo.SecWebSocketAccept = kv[1];
                        break;
                    case "Sec-WebSocket-Location":
                        acceptInfo.SecWebSocketLocation = kv[1];
                        break;
                    case "Sec-WebSocket-Origin":
                        acceptInfo.SecWebSocketOrigin = kv[1];
                        break;
                }
            }
            return acceptInfo;
        }
        public byte[] GetBytes(string content)
        {
            var buf = encoding.GetBytes(content);
            Data = new BufferSegment(buf);
            Data.Buffer = encoding.GetBytes(content);
            DataLength = Data.Buffer.LongLength;
            return EncodingToBytes();
        }
        public byte[] GetBytes(OpCodeType code = OpCodeType.Bin)
        {
            OpCode = (byte)code;
            DataLength = Data.Buffer.LongLength;
            return EncodingToBytes();
        }
    }

}
